<template>
  <div class="code-demo" ref="domRef">
    <div class="u-case" v-if="$slots.default" :style="demoStyle">
      <slot></slot>
    </div>
    <div class="u-bar">
      <el-link
        class="u-item"
        :icon="CopyDocument"
        :underline="false"
        @click="clickCopy"
      >
        复制代码
      </el-link>
      <el-link
        class="u-item"
        :icon="Document"
        :underline="false"
        @click="isShowCode = !isShowCode"
      >
        查看源代码
      </el-link>
    </div>
    <div
      class="u-code hljs"
      ref="codeRef"
      v-show="isShowCode"
      v-html="beautifiedCode"
    ></div>
    <div class="u-bar" v-show="isShowCode">
      <el-link
        class="u-item"
        :icon="ArrowUp"
        :underline="false"
        @click="clickHide"
      >
        隐藏源代码
      </el-link>
    </div>
  </div>
</template>

<script setup name="CodeDemo">
import { ref, computed, useSlots } from 'vue'
import { ElMessage } from 'element-plus'
import { CopyDocument, Document, ArrowUp } from '@element-plus/icons-vue'
import hljs from 'highlight.js'
import handlebars from 'highlight.js/lib/languages/handlebars'
import 'highlight.js/styles/base16/edge-light.css'
import { useClipboard } from '@vueuse/core'
const props = defineProps({
  demoStyle: Object,
})

// 包含slots：default，code
const slots = useSlots()

const domRef = ref()

const { copy } = useClipboard({ legacy: true })

const codeRef = ref()

// 是否显示code
const isShowCode = ref(false)

hljs.registerLanguage('handlebars', handlebars)

// 美化的代码
const beautifiedCode = computed(() => {
  return slots.code
    ? hljs.highlight(slots.code()[0].children.trim(), {
        language: 'handlebars',
      }).value
    : ''
})

// 点击复制代码
function clickCopy() {
  if (slots.code) {
    copy(slots.code()[0].children.trim())
    ElMessage.success('复制成功')
  }
}

// 点击隐藏代码
function clickHide() {
  isShowCode.value = false
  // console.log(domRef.value.offsetTop)

  // // + window.document.body.clientHeight / 2
  // window.scrollTo({
  //   top: domRef.value.offsetTop,
  //   behavior: 'smooth',
  // })
}
</script>

<style lang="scss" scoped>
.code-demo {
  border: 1px solid var(--el-border-color);
  border-radius: var(--el-border-radius-base);
  overflow: hidden;
  .u-case {
    padding: 10px;
    border-bottom: 1px solid var(--el-border-color);
  }
  .u-bar {
    display: flex;
    height: 40px;
    background-color: #fff;
    .u-item {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      height: 100%;
      border-left: 1px solid var(--el-border-color);
      &:first-child {
        border-left: none;
      }
    }
  }
  .u-code {
    padding: 10px;
    white-space: pre-wrap;
    font-family: Consolas, Monaco, monospace;
    font-size: 10pt;
  }
}
</style>
